package com.feilong.edgeAI.utils;


import java.util.HashMap;
import java.util.Map;

public class ChineseNumberConverter {

    // 中文数字到阿拉伯数字的映射
    private static final Map<String, Integer> chineseToArabicMap = new HashMap<>();

    static {
        chineseToArabicMap.put("一", 1);
        chineseToArabicMap.put("二", 2);
        chineseToArabicMap.put("三", 3);
        chineseToArabicMap.put("四", 4);
        chineseToArabicMap.put("五", 5);
        chineseToArabicMap.put("六", 6);
        chineseToArabicMap.put("七", 7);
        chineseToArabicMap.put("八", 8);
        chineseToArabicMap.put("九", 9);
        chineseToArabicMap.put("十", 10);
        for (int i = 1; i <= 9; i++) {
            String prefix = "十" + chineseToArabicMap.get(String.valueOf(i));
            chineseToArabicMap.put(prefix, 10 + i);
        }
        for (int i = 2; i <= 6; i++) {
            String prefix = i + "十";
            chineseToArabicMap.put(prefix, i * 10);
            for (int j = 1; j <= 9; j++) {
                String fullNumber = prefix + chineseToArabicMap.get(String.valueOf(j));
                chineseToArabicMap.put(fullNumber, i * 10 + j);
            }
        }
    }

    public static String convertChineseToArabic(String input) {
        StringBuilder sb = new StringBuilder(input);
        int i = 0;
        while (i < sb.length()) {
            int maxLength = 2; // 最长考虑两位数的中文表达
            if (i + maxLength <= sb.length() && chineseToArabicMap.containsKey(sb.substring(i, i + maxLength))) {
                int number = chineseToArabicMap.get(sb.substring(i, i + maxLength));
                sb.replace(i, i + maxLength, String.valueOf(number));
                i += String.valueOf(number).length(); // 更新索引位置
            } else if (i + 1 < sb.length() && chineseToArabicMap.containsKey(sb.substring(i, i + 1))) {
                // 处理单个字符的数字
                int number = chineseToArabicMap.get(sb.substring(i, i + 1));
                sb.replace(i, i + 1, String.valueOf(number));
                i++; // 更新索引位置
            } else {
                i++; // 跳过无法识别的字符
            }
        }

        return sb.toString();
    }
}